//
//  oldMomentPublishViewController.m
//  laonianbang
//
//  Created by 勇拓 李 on 18/4/2.
//  Copyright © 2018年 zaiyou. All rights reserved.
//

#import "oldMomentPublishViewController.h"
#import "VPImageCropperViewController.h"
#import "oldImage.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import "QNuploader.h"

#define placeholder_img [UIImage imageNamed:@"老年圈发表添加"]

@interface oldMomentPublishViewController ()<UITextViewDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate,VPImageCropperDelegate>
@property (weak, nonatomic) IBOutlet UITextView *text_view;
@property (weak, nonatomic) IBOutlet UILabel *label_placeholder;
@property (weak, nonatomic) IBOutlet UIImageView *img1;
@property (weak, nonatomic) IBOutlet UIImageView *img2;
@property (weak, nonatomic) IBOutlet UIImageView *img3;
@property (weak, nonatomic) IBOutlet UIButton *btn_publish;

@property (nonatomic, strong)NSMutableArray *imgArray;
@property (nonatomic, assign)NSInteger index;
@end

@implementation oldMomentPublishViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self initData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - initView
- (void)initView
{
    self.navigationItem.title = @"发表";
    _btn_publish.layer.cornerRadius = 6.f;
    
    _text_view.delegate = self;
    [_btn_publish addTarget:self action:@selector(btn_publish_tapped:) forControlEvents:UIControlEventTouchDown];
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoChooseImg1:)];
    [_img1 addGestureRecognizer:tap1];
    _img1.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoChooseImg2:)];
    [_img2 addGestureRecognizer:tap2];
    _img2.hidden = YES;
    _img2.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoChooseImg3:)];
    [_img3 addGestureRecognizer:tap3];
    _img3.hidden = YES;
    _img3.userInteractionEnabled = YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (_label_placeholder) {
        if ([textView.text length] == 0) {
            [_label_placeholder setHidden:NO];
        }
        else
        {
            [_label_placeholder setHidden:YES];
        }
    }
}

#pragma mark -img
- (void)gotoChooseImg1:(id)sender
{
    _index = 0;
    [self choosePic];
}

- (void)gotoChooseImg2:(id)sender
{
    _index = 1;
    [self choosePic];
}

- (void)gotoChooseImg3:(id)sender
{
    _index = 2;
    [self choosePic];
}

#pragma mark - initData
- (void)initData
{
    _imgArray = [NSMutableArray array];
}

- (void)btn_publish_tapped:(id)sender
{
    [self uploadImgs];
}

#pragma mark - 头像上传
- (void)uploadImgs
{
    [oldHub waiting:@"发表中"];
    
    if ([_imgArray count]) {
        WeakSelf
        
        NSMutableArray *array = [NSMutableArray array];
        
        NSInteger __block totalTime = 0;
        
        for (int i = 0; i < [_imgArray count]; i++) {
            UIImage *editedImage = _imgArray[i];
            
            [array addObject:[NSNull null]];
            
            NSString *uploadurl = [oldImage getImagePath:[oldImage compressImage:editedImage ratio:1.0]];
            [QiNiuShareInstance uploadImageToQNFilePath:uploadurl type:Image_file block:^(NSString *url) {
                
                if (url) {
                    totalTime++;
                    [array replaceObjectAtIndex:i withObject:url];
                    if (totalTime == [weakSelf.imgArray count]) {
                        [weakSelf uploadImgUrls:array];
                    }
                }
                else
                {
                    [oldHub warningUser:@"图片上传失败请重试"];
                }
            }];
        }
    }
    else
    {
        [self uploadImgUrls:nil];
    }
}

- (void)uploadImgUrls:(NSArray *)array
{
    WeakSelf
    
    NSCharacterSet  *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *text = [_text_view.text stringByTrimmingCharactersInSet:set];
    
    if (![text length] && (array == nil)) {
        [oldHub warningUser:@"不能发表空内容"];
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (text) {
        [params setObject:text forKey:@"content"];
    }
    
    NSString *imgUrls = nil;
    
    for (int i = 0; i < [array count]; i++) {
        if (i == 0) {
            imgUrls = array[i];
        }
        else
        {
            imgUrls = [NSString stringWithFormat:@"%@,%@", imgUrls, array[i]];
        }
    }
    
    if (imgUrls) {
        [params setObject:imgUrls forKey:@"pic"];
    }
    
    [OLDNetWork httpRequestWithPostPut:URL_Feed_AddFeed params:params success:^(id data) {
        [oldHub hideHUD];
        [oldHub warningUserAfterJump:@"发表成功" time:1.f];
        
        [weakSelf.navigationController popViewControllerAnimated:YES];
        
    } error:^(NSString *error) {
        [oldHub warningUser:error];
    }];
}

- (void)choosePic
{
    WeakSelf
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle: UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf selectFormPhotos];
    }];
    
    UIAlertAction *pictureAction = [UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf selectFormPicture];
    }];
    
    
    [alertController addAction:cancelAction];
    
    [alertController addAction:photoAction];
    
    [alertController addAction:pictureAction];
    
    if ([_imgArray count] >= (_index + 1)) {
        
        UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf deletePic];
        }];
        
        [alertController addAction:deleteAction];
    }
    
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)initImgs
{
    switch ([_imgArray count]) {
        case 0:
        {
            _img3.hidden = YES;
            _img2.hidden = YES;
            _img1.image = placeholder_img;
        }
            break;
        case 1:
        {
            _img3.hidden = YES;
            _img2.hidden = NO;
            _img2.image = placeholder_img;
            _img1.image = _imgArray[0];
        }
            break;
        case 2:
        {
            _img3.hidden = NO;
            _img2.hidden = NO;
            _img3.image = placeholder_img;
            _img2.image = _imgArray[1];
            _img1.image = _imgArray[0];
        }
            break;
        default:
        {
            _img3.hidden = NO;
            _img2.hidden = NO;
            _img3.image = _imgArray[2];
            _img2.image = _imgArray[1];
            _img1.image = _imgArray[0];
        }
            break;
    }
}

- (void)deletePic
{
    [_imgArray removeObjectAtIndex:_index];
    [self initImgs];
}

- (void)selectFormPhotos
{
    // 拍照
    if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([self isFrontCameraAvailable]) {
            controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
        }
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [self presentViewController:controller
                              animated:YES
                            completion:^(void){
                                NSLog(@"Picker View Controller is presented");
                            }];
    }
}

- (void)selectFormPicture
{
    // 从相册中选取
    if ([self isPhotoLibraryAvailable]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [self presentViewController:controller
                              animated:YES
                            completion:^(void){
                                NSLog(@"Picker View Controller is presented");
                            }];
    }
}

- (void)editHeadImg:(UIImage *)editedImage
{
    if ([_imgArray count] == _index) {
        [_imgArray addObject:editedImage];
    }
    else
    {
        [_imgArray replaceObjectAtIndex:_index withObject:editedImage];
    }
    
    [self initImgs];
}


#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [oldImage imageByScalingToMaxSize:portraitImg];
        // present the cropper view controller
        VPImageCropperViewController *imgCropperVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgCropperVC.delegate = self;
        [self presentViewController:imgCropperVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    [cropperViewController dismissViewControllerAnimated:NO completion:^{
        [self editHeadImg:editedImage];
    }];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark camera utility

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

@end
